package com.cs2.volunteerpostbackend.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cs2.volunteerpostbackend.po.Image;
import com.cs2.volunteerpostbackend.po.Moment;
import com.cs2.volunteerpostbackend.service.ContentCheckService;
import com.cs2.volunteerpostbackend.service.ImageService;
import com.cs2.volunteerpostbackend.service.MomentService;
import com.cs2.volunteerpostbackend.web.dto.RespEntity;
import com.cs2.volunteerpostbackend.web.dto.moment.MomentListDTO;
import com.cs2.volunteerpostbackend.web.dto.moment.MomentUserVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/moment")
public class MomentController {

    @Autowired
    private MomentService momentService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private ContentCheckService contentCheckService;

    /**
     * 分页获取动态列表（包含用户信息）
     * GET /moments/with-users?
     */
    @GetMapping("/user")
    public RespEntity getMomentsWithUsers(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam String userId,
            @RequestParam(defaultValue = "0") int type) {
        System.out.println("=== 接收查询动态请求 ===");
        System.out.println("参数: page=" + page + ", size=" + size + ", userId=" + userId + ", type=" + type);
        try {
            IPage<MomentUserVO> momentUserVOPage = momentService.listMomentsWithUserInfo(page, size, userId, type);
            System.out.println("查询成功，返回 " + momentUserVOPage.getRecords().size() + " 条记录");
            return new RespEntity("200", "查询成功", momentUserVOPage.getRecords());
        } catch (Exception e) {
            System.err.println("查询动态失败: " + e.getMessage());
            return new RespEntity("500", "查询失败: " + e.getMessage(), null);
        }
    }

    /**
     * 创建新动态
     * POST /api/moments
     */
    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public RespEntity createMoment(
            @RequestPart("moment") String momentStr,
            @RequestPart(value = "images", required = false) MultipartFile[] images,
            @RequestPart(value = "external_links", required = false) String externalLinksStr
    ) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        Moment moment = mapper.readValue(momentStr, Moment.class);


        // 内容检查
        if (contentCheckService.containsSensitiveContent(moment.getContent())) {
            return RespEntity.error("包含敏感值");
        }

        System.out.println("=== 接收创建动态请求 ===");
        System.out.println("标题: " + moment.getTitle());
        try {
            // 创建动态
            Moment createdMoment = momentService.createMoment(moment);
            System.out.println("创建成功，动态ID: " + createdMoment.getId());

            // 如果存在外部链接，先在后端进行下载处理，下载完成后处理图片存储
            if (externalLinksStr != null && !externalLinksStr.isEmpty()) {

                // 将json转换为对应的字符串数组
                String[] externalLinksArray = mapper.readValue(externalLinksStr, String[].class);
                List<String> externalLinks = Arrays.asList(externalLinksArray);

                List<String> imageIds = new ArrayList<>();

                for (String imageUrl : externalLinks) {
                    if (imageUrl != null && !imageUrl.isEmpty()) {
                        // 从URL下载图片并保存
                        Image savedImage = imageService.downloadImageFromUrl(
                                imageUrl,
                                createdMoment.getPosterId(),
                                createdMoment.getId()
                        );

                        // 建立动态和图片的关系
                        imageService.saveMomentImageRelation(createdMoment.getId(), savedImage.getId());

                        imageIds.add(savedImage.getId());
                        System.out.println("从链接下载图片成功，ID: " + savedImage.getId());
                    }
                }
                System.out.println("共下载 " + imageIds.size() + " 张图片");
            }

            // 如果有图片上传，处理图片存储
            if (images != null && images.length > 0) {
                List<String> imageIds = new ArrayList<>();

                // 保存每张图片
                for (MultipartFile imageFile : images) {
                    if (imageFile != null && !imageFile.isEmpty()) {
                        // 保存图片到文件系统并创建图片记录
                        Image savedImage = imageService.saveImage(
                                imageFile,
                                createdMoment.getPosterId(),
                                createdMoment.getId()
                        );

                        // 建立动态和图片的关系
                        imageService.saveMomentImageRelation(createdMoment.getId(), savedImage.getId());

                        imageIds.add(savedImage.getId());
                        System.out.println("图片保存成功，ID: " + savedImage.getId());
                    }
                }
                System.out.println("共保存 " + imageIds.size() + " 张图片");
            }

            return new RespEntity("200", "创建成功", createdMoment);
        } catch (Exception e) {
            System.err.println("创建动态失败: " + e.getMessage());
            return new RespEntity("500", "创建失败: " + e.getMessage(), null);
        }
    }

    /**
     * 更新动态
     * PUT /api/moments/{id}
     */
    @PutMapping("/{id}")
    public RespEntity updateMoment(@PathVariable String id, @RequestBody Moment moment) {

        // 内容检查
        if (contentCheckService.containsSensitiveContent(moment.getContent())) {
            return RespEntity.error("包含敏感值");
        }

        System.out.println("=== 接收更新动态请求 ===");
        System.out.println("动态ID: " + id);
        try {
            moment.setId(id); // 确保ID一致
            Moment updatedMoment = momentService.updateMoment(moment);
            System.out.println("更新成功，动态ID: " + updatedMoment.getId());
            return new RespEntity("200", "更新成功", updatedMoment);
        } catch (Exception e) {
            System.err.println("更新动态失败: " + e.getMessage());
            return new RespEntity("500", "更新失败: " + e.getMessage(), null);
        }
    }

    /**
     * 点赞动态
     * PUT /api/moments/{id}/like
     */
    @PutMapping("/like")
    public RespEntity likeMoment(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        System.out.println("=== 接收点赞请求 ===");
        System.out.println("动态ID: " + id);
        try {
            Moment likedMoment = momentService.increaseLikeCount(id);
            System.out.println("点赞成功，当前点赞数: " + likedMoment.getLikeCount());
            return new RespEntity("200", "点赞成功", likedMoment);
        } catch (Exception e) {
            System.err.println("点赞失败: " + e.getMessage());
            return new RespEntity("500", "点赞失败: " + e.getMessage(), null);
        }
    }

    /**
     * 删除动态
     * DELETE /api/moments/{id}
     */
    @DeleteMapping()
    public RespEntity deleteMoment(@PathParam("id") String id) {
        System.out.println("=== 接收删除动态请求 ===");
        System.out.println("动态ID: " + id);
        try {
            int rows = momentService.deleteMoment(id);
            System.out.println("删除成功");
            String msg = "删除成功, 影响行数: " + rows;
            return new RespEntity("200", "删除成功", msg);
        } catch (Exception e) {
            System.err.println("删除动态失败: " + e.getMessage());
            return new RespEntity("500", "删除失败: " + e.getMessage(), null);
        }
    }


    /** 新加入的内容 **/
    @PostMapping("/like/batch")
    public RespEntity likeBatchMoments(@RequestBody MomentListDTO momentListDTO) {
        System.out.println("=== 接收批量点赞请求 ===");
        List<Moment> momentList = new ArrayList<>();
        try {
            for (String momentId : momentListDTO.getMomentIdList()) {
                Moment likedMoment = momentService.increaseLikeCount(momentId);
                momentList.add(likedMoment);
                System.out.println("moment id: " + momentId + " 点赞成功，当前点赞数: " + likedMoment.getLikeCount());
            }
            return new RespEntity("200", "点赞成功", momentList);
        } catch (Exception e) {
            System.err.println("点赞失败: " + e.getMessage());
            return new RespEntity("500", "点赞失败: " + e.getMessage(), null);
        }
    }

    @PostMapping("/delete/batch")
    public RespEntity deleteBatchMoments(@RequestBody MomentListDTO momentListDTO) {
        System.out.println("=== 接收批量删除请求 ===");
        try {
            int rows = 0;
            for (String momentId : momentListDTO.getMomentIdList()) {
                rows += momentService.deleteMoment(momentId);
            }
            return new RespEntity("200", "删除成功，影响行数: " + rows, null);
        } catch (Exception e) {
            System.err.println("删除动态失败: " + e.getMessage());
            return new RespEntity("500", "删除失败: " + e.getMessage(), null);
        }
    }
}